import { createRouter, createWebHistory } from 'vue-router'
import { useUserStore } from '../store/user' // 导入你的用户store
import Layout from '../components/Layout.vue' // 导入 Layout 组件

const routes = [
  { 
    path: '/login', 
    name: 'Login', // 添加 name 方便跳转
    component: () => import('../views/Login.vue'),
    meta: { requiresAuth: false } // 登录页不需要认证
  },
  {
    path: '/',
    name: 'Layout', // Layout 路由的名称
    component: Layout, // 使用 Layout 作为父组件
    redirect: '/', // 默认重定向到首页，防止 / 访问 Layout 自身
    meta: { requiresAuth: true },
    children: [ // 所有需要布局的页面都作为 Layout 的子路由
      {
        path: '', // 空路径表示默认子路由，即 / 时显示 Dashboard
        name: 'Dashboard',
        component: () => import('../views/Dashboard.vue'),
        meta: { requiresAuth: true }
      },
      { 
        path: 'users', 
        name: 'UserManage',
        component: () => import('../views/UserManage.vue'),
        meta: { requiresAuth: true }
      },
      { 
        path: 'inquiry', 
        name: 'InquiryManage',
        component: () => import('../views/InquiryManage.vue'),
        meta: { requiresAuth: true }
      },
      { 
        path: 'healthcheck', 
        name: 'HealthCheckManage',
        component: () => import('../views/HealthCheckManage.vue'),
        meta: { requiresAuth: true }
      },
      { 
        path: 'chronic', 
        name: 'ChronicManage',
        component: () => import('../views/ChronicManage.vue'),
        meta: { requiresAuth: true }
      },
      { 
        path: 'plan', 
        name: 'PlanManage',
        component: () => import('../views/PlanManage.vue'),
        meta: { requiresAuth: true }
      },
      { 
        path: 'diet', 
        name: 'DietManage',
        component: () => import('../views/DietManage.vue'),
        meta: { requiresAuth: true }
      },
      { 
        path: 'exercise', 
        name: 'ExerciseManage',
        component: () => import('../views/ExerciseManage.vue'),
        meta: { requiresAuth: true }
      },
      { 
        path: 'lecture', 
        name: 'HealthLectureManage',
        component: () => import('../views/HealthLectureManage.vue'),
        meta: { requiresAuth: true }
      },
      { 
        path: 'registration', 
        name: 'LectureRegistrationManage',
        component: () => import('../views/LectureRegistrationManage.vue'),
        meta: { requiresAuth: true }
      },
    ]
  },
  // 添加一个捕获所有未匹配路由的路由，重定向到首页或404页
  { 
    path: '/:catchAll(.*)', 
    redirect: '/' 
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

router.beforeEach((to, from, next) => {
  const userStore = useUserStore();
  // 检查路由是否需要认证
  if (to.meta.requiresAuth && !userStore.token) {
    // 如果需要认证但用户没有token，则重定向到登录页
    next('/login');
  } else if (to.path === '/login' && userStore.token) {
    // 如果用户已登录且尝试访问登录页，则重定向到首页
    next('/');
  } else {
    // 否则正常放行
    next();
  }
});

export default router 